// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: 'education-6gwexwp8488514df' })

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const { bookId } = event

  try {
    console.log('接收到的bookId:', bookId);

    // 先获取所有bookAddresses记录
    const bookAddresses = await db.collection('bookAddresses')
      .where({
        bookId: bookId
      })
      .orderBy('createTime', 'desc')
      .get()

    console.log('查询到的bookAddresses:', bookAddresses.data);

    // 如果没有记录，直接返回空数组
    if (!bookAddresses.data || bookAddresses.data.length === 0) {
      return {
        success: true,
        data: []
      }
    }

    // 获取所有地址ID
    const addressIds = bookAddresses.data.map(item => item.addressId)
    console.log('地址ID列表:', addressIds);

    // 查询对应的地址信息
    const addresses = await db.collection('addresses')
      .where({
        _id: db.command.in(addressIds)
      })
      .get()

    console.log('查询到的addresses:', addresses.data);

    // 合并数据
    const addressMap = {}
    addresses.data.forEach(addr => {
      addressMap[addr._id] = addr
    })

    const result = bookAddresses.data
      .filter(item => addressMap[item.addressId]) // 确保地址存在
      .map(item => ({
        _id: item._id,
        phone: addressMap[item.addressId].phone,
        remark: addressMap[item.addressId].remark,
        createTime: item.createTime
      }))

    console.log('最终结果:', result);

    return {
      success: true,
      data: result
    }
  } catch (err) {
    console.error('云函数执行错误:', err);
    return {
      success: false,
      error: err.message || '未知错误'
    }
  }
} 